<template>
  <div class="clue-center">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <div class="left-actions">
        <el-button type="danger" @click="showCreateDialog" :icon="Plus">新建线索</el-button>
        <el-button :icon="Refresh" @click="refreshList">刷新列表</el-button>
      </div>

      <div class="right-filters">
        <el-select
          v-model="filterStatus"
          placeholder="所有状态"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-select
          v-model="filterUrgency"
          placeholder="所有优先级"
          clearable
          style="width: 130px"
        >
          <el-option
            v-for="item in urgencyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-input
          v-model="searchText"
          placeholder="搜索线索..."
          clearable
          style="width: 200px"
          :prefix-icon="Search"
        />
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="8" :md="6" v-for="stat in stats" :key="stat.title">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" :style="{ background: stat.color }">
                <el-icon><component :is="stat.icon" /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">{{ stat.title }}</div>
                <div class="stat-value">{{ stat.value }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 线索列表 -->
    <div class="clue-list" style="height: 400px">
      <el-row :gutter="20">
        <el-col
          v-for="clue in paginatedClues"
          :key="clue.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card class="clue-card" shadow="hover">
            <div class="card-header">
              <div class="status-tags">
                <el-tag
                  :type="statusTagMap[clue.status]"
                  effect="dark"
                  class="status-tag"
                  size="small"
                >
                  {{ clue.status }}
                </el-tag>
                <el-tag
                  :type="clue.urgency === '高' ? 'danger' : 'warning'"
                  effect="plain"
                  size="small"
                >
                  <el-icon><AlarmClock /></el-icon>
                  {{ clue.urgency }}优先级
                </el-tag>
              </div>
              <div class="clue-id">#{{ clue.id }}</div>
            </div>

            <div class="card-body">
              <h3 class="clue-title">{{ clue.title }}</h3>
              <div class="clue-meta">
                <span class="type">
                  <el-icon><Collection /></el-icon>
                  {{ clue.type }}
                </span>
                <el-divider direction="vertical" />
                <span class="author">
                  <el-icon><User /></el-icon>
                  {{ clue.author }}
                </span>
              </div>
              <div class="clue-time">
                <el-icon><Clock /></el-icon>
                {{ formatTime(clue.createTime) }}
              </div>
            </div>

            <div class="card-actions">
              <el-button
                type="danger"
                plain
                size="small"
                @click.stop="showDetailDialog(clue)"
              >
                处理进展
              </el-button>
              <el-button
                type="danger"
                :icon="ChatDotRound"
                circle
                size="small"
                @click.stop="showCommentDialog(clue)"
              />
              <el-dropdown @click.stop>
                <el-button type="danger" :icon="More" circle size="small" />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="editClue(clue)">
                      <el-icon><Edit /></el-icon>编辑线索
                    </el-dropdown-item>
                    <el-dropdown-item @click="deleteClue(clue)" divided>
                      <el-icon><Delete /></el-icon>删除线索
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[8, 16, 24]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredClues.length"
        background
      />
    </div>

    <!-- 新建/编辑线索弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="currentClue?.id ? '编辑线索' : '新建线索'"
      width="600px"
    >
      <el-form
        ref="clueForm"
        :model="currentClue"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="线索标题" prop="title">
          <el-input v-model="currentClue.title" />
        </el-form-item>

        <el-form-item label="详细内容" prop="content">
          <el-input
            v-model="currentClue.content"
            type="textarea"
            :rows="4"
            resize="none"
            show-word-limit
            maxlength="500"
          />
        </el-form-item>

        <el-form-item label="紧急程度" prop="urgency">
          <el-select v-model="currentClue.urgency">
            <el-option
              v-for="item in urgencyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="线索类型" prop="type">
          <el-select v-model="currentClue.type">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="submitClue">提交</el-button>
      </template>
    </el-dialog>

    <!-- 线索详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`${currentClue?.title} - 处理进展`"
      width="800px"
    >
      <div class="timeline-wrapper">
        <el-timeline>
          <el-timeline-item
            v-for="record in currentClue?.timeline"
            :key="record.time"
            :timestamp="formatTime(record.time)"
            placement="top"
            :type="getTimelineType(record.type)"
            :icon="getTimelineIcon(record.type)"
            :color="getTimelineColor(record.type)"
          >
            <el-card shadow="never">
              <template #header>
                <div class="record-header">
                  <span class="record-type">{{ record.type }}</span>
                  <span class="record-operator">{{ record.operator }}</span>
                </div>
              </template>
              <div class="record-content">{{ record.content }}</div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <!-- 评论弹窗 -->
    <el-dialog
      v-model="commentDialogVisible"
      :title="`协作讨论 - ${currentClue?.title}`"
      width="600px"
    >
      <div class="comment-section">
        <div class="comment-list">
          <div v-for="comment in currentClue?.comments" :key="comment.time" class="comment-item">
            <div class="comment-header">
              <span class="comment-author">{{ comment.author }}</span>
              <span class="comment-time">{{ formatTime(comment.time) }}</span>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
          </div>
        </div>
        <el-input
          v-model="commentContent"
          type="textarea"
          :rows="3"
          placeholder="请输入协作意见或补充内容"
          resize="none"
          class="comment-input"
        />
        <div class="comment-actions">
          <el-button type="danger" @click="submitComment">提交评论</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ref, computed, onMounted
} from 'vue'
import {
  Plus, Search, Refresh, ChatDotRound, More,
  Edit, Delete, AlarmClock, Collection, User, Clock, Loading
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'

interface TimelineRecord {
  time: string
  type: string
  content: string
  operator: string
}

interface Clue {
  id: number
  title: string
  content: string
  author: string
  status: string
  urgency: string
  type: string
  createTime: string
  timeline: TimelineRecord[]
  comments: {
    time: string
    author: string
    content: string
  }[]
}

// 状态配置
const statusOptions = [
  { value: '待处理', label: '待处理' },
  { value: '调查中', label: '调查中' },
  { value: '已解决', label: '已解决' },
  { value: '已关闭', label: '已关闭' }
]

const urgencyOptions = [
  { value: '高', label: '高优先级' },
  { value: '中', label: '中优先级' },
  { value: '低', label: '低优先级' }
]

const typeOptions = [
  { value: '目击线索', label: '目击线索' },
  { value: '监控录像', label: '监控录像' },
  { value: '物品发现', label: '物品发现' },
  { value: '交通信息', label: '交通信息' },
  { value: '其他', label: '其他' }
]

// 响应式状态
const clues = ref<Clue[]>([])
const currentClue = ref<Partial<Clue>>({
  title: '',
  content: '',
  urgency: '中',
  type: '目击线索',
  status: '待处理'
})
const commentContent = ref('')
const filterStatus = ref('')
const filterUrgency = ref('')
const searchText = ref('')
const currentPage = ref(1)
const pageSize = ref(8)
const editDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const commentDialogVisible = ref(false)
const clueForm = ref<FormInstance>()

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入线索标题', trigger: 'blur' },
    { min: 5, max: 50, message: '长度在5到50个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入详细内容', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在10到500个字符', trigger: 'blur' }
  ],
  urgency: [{ required: true, message: '请选择紧急程度', trigger: 'change' }],
  type: [{ required: true, message: '请选择线索类型', trigger: 'change' }]
}

// 添加状态标签映射
const statusTagMap: Record<string, string> = {
  '待处理': 'warning',
  '调查中': 'info',
  '已解决': 'success',
  '已关闭': 'success'
}

// 计算属性
const filteredClues = computed(() => {
  return clues.value.filter(clue => {
    const statusMatch = filterStatus.value ? clue.status === filterStatus.value : true
    const urgencyMatch = filterUrgency.value ? clue.urgency === filterUrgency.value : true
    const searchMatch = searchText.value ?
      clue.title.includes(searchText.value) ||
      clue.content.includes(searchText.value) ||
      clue.author.includes(searchText.value) : true
    return statusMatch && urgencyMatch && searchMatch
  })
})

const paginatedClues = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredClues.value.slice(start, end)
})

const stats = computed(() => [
  {
    title: '总线索数',
    value: clues.value.length,
    icon: Collection,
    color: '#f56c6c'
  },
  {
    title: '待处理',
    value: clues.value.filter(c => c.status === '待处理').length,
    icon: AlarmClock,
    color: '#e6a23c'
  },
  {
    title: '进行中',
    value: clues.value.filter(c => c.status === '调查中').length,
    icon: Loading,
    color: '#409eff'
  }
])

// 方法
const formatTime = (time: string) => {
  return new Date(time).toLocaleString()
}

const showCreateDialog = () => {
  currentClue.value = {
    title: '',
    content: '',
    urgency: '中',
    type: '目击线索',
    status: '待处理'
  }
  editDialogVisible.value = true
}

const editClue = (clue: Clue) => {
  currentClue.value = { ...clue }
  editDialogVisible.value = true
}

const deleteClue = async (clue: Clue) => {
  try {
    await ElMessageBox.confirm('确定要删除这条线索吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    clues.value = clues.value.filter(c => c.id !== clue.id)
    ElMessage.success('删除成功')
  } catch {}
}

const submitClue = async () => {
  if (!clueForm.value) return
  const valid = await clueForm.value.validate()
  if (!valid) return

  if (currentClue.value.id) {
    // 更新线索
    const index = clues.value.findIndex(c => c.id === currentClue.value.id)
    if (index >= 0) {
      clues.value.splice(index, 1, {
        ...clues.value[index],
        ...currentClue.value,
        timeline: [
          ...clues.value[index].timeline,
          {
            time: new Date().toISOString(),
            type: '信息更新',
            content: '线索信息被修改',
            operator: '当前用户'
          }
        ]
      })
    }
  } else {
    // 新建线索
    const newClue: Clue = {
      ...currentClue.value,
      id: Date.now(),
      author: '当前用户',
      createTime: new Date().toISOString(),
      timeline: [
        {
          time: new Date().toISOString(),
          type: '线索提交',
          content: currentClue.value.content || '',
          operator: '当前用户'
        }
      ],
      comments: []
    } as Clue
    clues.value.unshift(newClue)
  }

  editDialogVisible.value = false
  ElMessage.success('操作成功')
}

const submitComment = () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  if (currentClue.value.id) {
    const clue = clues.value.find(c => c.id === currentClue.value.id)
    if (clue) {
      clue.comments.push({
        time: new Date().toISOString(),
        author: '当前用户',
        content: commentContent.value
      })
      commentContent.value = ''
      ElMessage.success('评论提交成功')
    }
  }
  commentDialogVisible.value = false
}

const refreshList = () => {
  currentPage.value = 1
  ElMessage.success('已刷新')
}

// 时间线样式处理
const getTimelineType = (type: string) => {
  const types: Record<string, string> = {
    '线索提交': 'primary',
    '信息更新': 'warning',
    '状态变更': 'success',
    '协作评论': 'info'
  }
  return types[type] || 'primary'
}

const getTimelineIcon = (type: string) => {
  const icons: Record<string, string> = {
    '线索提交': 'document-add',
    '信息更新': 'edit',
    '状态变更': 'refresh',
    '协作评论': 'chat-dot-round'
  }
  return icons[type] || 'document'
}

const getTimelineColor = (type: string) => {
  const colors: Record<string, string> = {
    '线索提交': '#f56c6c',
    '信息更新': '#e6a23c',
    '状态变更': '#67c23a',
    '协作评论': '#409eff'
  }
  return colors[type] || '#909399'
}

// 添加显示详情对话框的方法
const showDetailDialog = (clue: Clue) => {
  currentClue.value = clue
  detailDialogVisible.value = true
}

// 添加显示评论对话框的方法
const showCommentDialog = (clue: Clue) => {
  currentClue.value = clue
  commentDialogVisible.value = true
}

// 初始化数据
onMounted(() => {
  // 添加模拟数据
  clues.value = [
    {
      id: 1,
      title: '目击者报告',
      content: '在某地目击到可疑人员。',
      author: '张三',
      status: '待处理',
      urgency: '高',
      type: '目击线索',
      createTime: new Date().toISOString(),
      timeline: [
        {
          time: new Date().toISOString(),
          type: '线索提交',
          content: '目击者提交了报告',
          operator: '张三'
        }
      ],
      comments: []
    },
    {
      id: 2,
      title: '监控录像',
      content: '监控录像显示可疑车辆经过。',
      author: '李四',
      status: '调查中',
      urgency: '中',
      type: '监控录像',
      createTime: new Date().toISOString(),
      timeline: [
        {
          time: new Date().toISOString(),
          type: '线索提交',
          content: '监控录像被提交',
          operator: '李四'
        },
        {
          time: new Date().toISOString(),
          type: '状态变更',
          content: '线索状态变更为调查中',
          operator: '管理员'
        }
      ],
      comments: []
    },
    {
      id: 3,
      title: '物品发现',
      content: '在某地发现可疑物品。',
      author: '王五',
      status: '已解决',
      urgency: '低',
      type: '物品发现',
      createTime: new Date().toISOString(),
      timeline: [
        {
          time: new Date().toISOString(),
          type: '线索提交',
          content: '发现可疑物品并提交线索',
          operator: '王五'
        },
        {
          time: new Date().toISOString(),
          type: '状态变更',
          content: '线索状态变更为已解决',
          operator: '管理员'
        }
      ],
      comments: []
    }
  ]
})
</script>

<style lang="scss" scoped>
/* 线索协作中心全局样式 */
.clue-center {
  padding: 10px;
  width: 100%;
  margin: 0 auto;
  height: 100%;

  /* 操作栏样式 */
  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding: 5px 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);

    .left-actions {
      display: flex;
      gap: 12px;

      .el-button {
        padding: 10px 20px;
        border-radius: 6px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(208, 48, 80, 0.2);
        }
      }
    }

    .right-filters {
      display: flex;
      gap: 12px;
      align-items: center;

      .el-input,
      .el-select {
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 2px 8px rgba(208, 48, 80, 0.1);
        }
      }
    }
  }

  /* 统计卡片样式 */
  .stats-cards {
    margin-bottom: 10px;

    .stat-card {
      border-radius: 8px;
      transition: transform 0.3s ease;
      margin: 10px;
      border: 1px solid #e6e6e6;

      &:hover {
        transform: translateY(-5px);
      }

      .stat-content {
        display: flex;
        align-items: center;
        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;
          font-size: 24px;
          color: #fff;
          transition: all 0.3s ease;
        }

        .stat-info {
          flex: 1;

          .stat-title {
            color: #606266;
            font-size: 14px;
            margin-bottom: 4px;
          }

          .stat-value {
            color: #303133;
            font-size: 24px;
            font-weight: 600;
          }
        }
      }
    }
  }

  /* 线索卡片样式 */
  .clue-card {
    margin-bottom: 20px;
    border-radius: 12px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
    max-width: 300px;
    width: 100%;
    border: 1px solid #e6e6e6;
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 16px rgba(208, 48, 80, 0.15);
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .status-tags {
        display: flex;
        gap: 8px;

        .el-tag {
          font-weight: 500;
          letter-spacing: 0.5px;
        }
      }

      .clue-id {
        color: #909399;
        font-size: 12px;
        font-family: monospace;
      }
    }

    .card-body {
      padding: 8px 0;

      .clue-title {
        color: #d03050;
        font-size: 16px;
        margin: 0 0 12px;
        line-height: 1.4;
        font-weight: 600;
      }

      .clue-meta {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #606266;
        font-size: 12px;
        margin-bottom: 8px;

        .el-icon {
          margin-right: 4px;
          vertical-align: middle;
        }

        .type {
          color: #d03050;
          font-weight: 500;
        }
      }

      .clue-time {
        color: #909399;
        font-size: 12px;
        display: flex;
        align-items: center;

        .el-icon {
          margin-right: 6px;
        }
      }
    }

    .card-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 12px;
      border-top: 1px solid #ebeef5;

      .el-button {
        padding: 8px 16px;
        border-radius: 20px;

        &--circle {
          padding: 8px;
        }
      }

      .el-dropdown {
        margin-left: auto;
      }
    }
  }

  /* 分页样式 */
  .pagination {
    margin-top: 24px;
    display: flex;
    justify-content: center;

    .el-pagination {
      padding: 12px 16px;
      border-radius: 8px;
    }
  }

  /* 弹窗样式 */
  .el-dialog {
    border-radius: 12px;

    &__header {
      background: linear-gradient(135deg, #ffecef, #ffffff);
      border-radius: 12px 12px 0 0;
      padding: 20px 24px;
      margin-right: 0;

      .el-dialog__title {
        color: #d03050;
        font-weight: 600;
        font-size: 18px;
      }
    }

    &__body {
      padding: 20px 24px;

      .timeline-wrapper {
        max-height: 60vh;
        overflow-y: auto;
        padding-right: 12px;

        .el-timeline {
          padding-left: 24px;

          .el-timeline-item {
            padding-bottom: 24px;

            &__node {
              width: 16px;
              height: 16px;
              left: -2px;
            }

            &__timestamp {
              font-size: 13px;
            }

            .el-card {
              border-radius: 8px;
              border: 1px solid #f0f0f0;

              &__header {
                padding: 12px 16px;

                .record-header {
                  display: flex;
                  justify-content: space-between;
                  font-size: 13px;

                  .record-type {
                    color: #d03050;
                    font-weight: 500;
                  }

                }
              }

              .record-content {
                line-height: 1.6;
                padding: 12px 16px;
              }
            }
          }
        }
      }

      .comment-section {
        .comment-list {
          max-height: 300px;
          overflow-y: auto;
          margin-bottom: 20px;

          .comment-item {
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 12px;

            .comment-header {
              display: flex;
              justify-content: space-between;
              margin-bottom: 8px;
              font-size: 12px;

              .comment-author {
                color: #d03050;
                font-weight: 500;
              }

            }

            .comment-content {
              line-height: 1.5;
            }
          }
        }

        .comment-input {
          margin-bottom: 16px;

          textarea {
            border-radius: 8px;
          }
        }

        .comment-actions {
          text-align: right;
        }
      }
    }
  }
}

/* 全局覆盖样式 */
:root {
  --el-color-danger: #d03050;
  --el-color-primary: #d03050;
}

.el-button--danger {
  &:hover,
  &:focus {
    background-color: #f56c6c;
    border-color: #f56c6c;
  }

  &.is-plain {
    color: #d03050;
    border-color: rgba(208, 48, 80, 0.5);

    &:hover {
      background-color: rgba(208, 48, 80, 0.08);
    }
  }
}

.el-tag--danger {
  background-color: rgba(208, 48, 80, 0.1);
  border-color: rgba(208, 48, 80, 0.2);
  color: #d03050;
}

.el-pagination.is-background .el-pager li:not(.is-disabled).is-active {
  background-color: #d03050;
}
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #ff4444;
}
</style>
